//
//  AutoRequest.swift
//  Auto114
//
//  Created by yb on 2020/8/24.
//  Copyright © 2020 RMCtl. All rights reserved.
//

import Foundation
import Alamofire

let baseUrl = "https://www.114yygh.com/mobile/"
let cooikes = "cmi-user-ticket=Pe1lrOtNXAPCmRC5nWNZ032TJkf1aebalJ1uww..; hyde_session=U7nFMqG7QEfOKy8b9NEoTE3761m3iCGn_5327570; _opt=mobile_wxauth_8e0ccc892d7caa4356f1cd16eaf66209; __jsluid_h=2084bfce993d44c721cc8a378dc3e6c8; __jsluid_s=fdfa354a805f2280e76f17eb1eb209c8"

let UA = "Mozilla/5.0 (iPhone; CPU iPhone OS 15_4 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148 MicroMessenger/8.0.36(0x18002427) NetType/WIFI Language/zh_CN"
let netSession: Session =  {
    let s = URLSessionConfiguration.default
    s.httpAdditionalHeaders = ["Request-Source": "WE_CHAT", "User-Agent": UA, "Accept-Language": "zh-cn"]
    
    var cookieProperties: [HTTPCookiePropertyKey: Any] = [
        .domain: ".114yygh.com",
        .path: "/"
    ]
    cookieProperties[.name] = "cmi-user-ticket"
    cookieProperties[.value] = "xy5nQzUiKBQXI0ZHMvzvKVK4yYuTt0DZeYpcWA.."
    if let cookie = HTTPCookie(properties: cookieProperties) {
        HTTPCookieStorage.shared.setCookie(cookie)
    }
    cookieProperties[.name] = "imed_session_tm"
    cookieProperties[.value] = "\(Int(Date().timeIntervalSince1970))"
    if let cookie = HTTPCookie(properties: cookieProperties) {
        HTTPCookieStorage.shared.setCookie(cookie)
    }
    cookieProperties[.name] = "imed_session"
    cookieProperties[.value] = "aZ1thEDgd1IUbZgmMS17slxvN38gfi2d_5608874"
    if let cookie = HTTPCookie(properties: cookieProperties) {
        HTTPCookieStorage.shared.setCookie(cookie)
    }
    cookieProperties[.name] = "_opt"
    cookieProperties[.value] = "mobile_wxauth_8e0ccc892d7caa4356f1cd16eaf66209"
    if let cookie = HTTPCookie(properties: cookieProperties) {
        HTTPCookieStorage.shared.setCookie(cookie)
    }
    
    return Session(configuration: s)
}()



var ts: Int {
    Int(Date().timeIntervalSince1970*1000)
}

var headers: HTTPHeaders {
    HTTPHeaders(["Request-Source": "UNICOM_SERVICE",
                 "Referer": "https://www.114yygh.com/bjwechat/"])
//    HTTPHeaders(["Cookie": cooikes])
}



extension Worker {
    
    func getUrl(_ url: String, params: Parameters? = nil, complete:@escaping (AFDataResponse<Any>) -> Void) {
        LogViewUtility.log("\(name) getUrl: \(url)")
        netSession.request(url, parameters: params, headers: headers).responseJSON { (resp) in
            complete(resp)
        }
    }

    func postUrl(_ url: String, params: Parameters? = nil, complete:@escaping (AFDataResponse<Any>) -> Void) {
        LogViewUtility.log("\(name) postUrl: \(url)")
        netSession.request(url, method: .post, parameters: params, encoding: JSONEncoding.default, headers: headers).responseJSON { (resp) in
            complete(resp)
        }
    }

    func getProductList(complete: @escaping ([[String: Any]]?) -> Void) {
        let url =  baseUrl + "product/detail?_time=\(ts)"
        
        postUrl(url, params: ["hosCode": hospitalCode,
                                  "firstDeptCode": firstDeptCode,
                                  "secondDeptCode": secondDeptCode,
                                  "target": targetDate
        ]) { (resp) in
            guard let json = resp.result.any as? [String: Any], let data = json["data"] as? [[String: Any]] else {
                complete(nil)
                return
            }
            complete(data)
        }
        
    }

    struct Product {
        let key: String
        let dutyTime: String?
    }

    func findTargetProduct(in data: [[String: Any]]) -> Product? {
        for periodInfo in data {
            guard let detail = periodInfo["detail"] as? [[String: Any]] else {
                continue
            }
            for one in detail {
                guard let productKey = one["uniqProductKey"] as? String else {
                    continue
                }
                guard let docName = one["doctorName"] as? String, docName == doctorName else {
                    continue
                }
//                if let remainder = one["ncode"] as? String, remainder != "&#xf120;" {
                    return Product(key: productKey, dutyTime: nil)
//                }
            }
        }
        return nil
    }

    func comfirmProduct(product: Product, complete: @escaping (Bool) -> Void) {
        let url = baseUrl + "product/confirm?_time=\(ts)"
        postUrl(url, params: [
            "hosCode": hospitalCode,
            "firstDeptCode": firstDeptCode,
            "secondDeptCode": secondDeptCode,
            "target": targetDate,
            "uniqProductKey": product.key,
            "dutyTime": product.dutyTime ?? 0
        ]) { (resp) in
            guard let json = resp.result.any as? [String: Any],
                let code = json["resCode"] as? Int, code == 0 else {
                complete(false)
                return
            }
            complete(true)
        }

    }

    func survey(complete: @escaping (Bool) -> Void) {
        let url = baseUrl + "terse/survey/result"
        
        getUrl(url, params: ["_time": ts, "code": "reg_ncp_survey", "hosCode": hospitalCode]) { (resp) in
            guard let json = resp.result.any as? [String: Any],
                let code = json["resCode"] as? Int, code == 0 else {
                complete(false)
                return
            }
            complete(true)
        }
    }

    func order(product: Product, code: String, complete: @escaping (Bool) -> Void) {
        let checkUrl = baseUrl + "order/save/check?_time=\(ts)"
        var params: [String: Any] = [
            "hosCode": hospitalCode,
            "firstDeptCode": firstDeptCode,
            "secondDeptCode": secondDeptCode,
            "treatmentDay": targetDate,
            "uniqProductKey": product.key,
            "cardType": cardType,
            "cardNo": cardNumber,
            "smsCode": code,
            "jytCardId": "",
            "hospitalCardId": "",
            "phone": phoneNumber,
            "dutyTime": product.dutyTime ?? 0,
            "contactIdCardNo": "500101198809307987",
            "contactIdCardType": "IDENTITY_CARD",
            "contactPhone": "17710680010",
            "contactUsername": "何沁洁"
        ]
        
        func requestSave() {
            params["orderFrom"] = "HOSP"
            let orderUrl = baseUrl + "order/save?_time=\(ts)"
            postUrl(orderUrl,params: params) { (resp) in
                guard let json = resp.result.any as? [String: Any] else {
                    complete(false)
                    return
                }
                LogViewUtility.log("save order result: \(self.name) \n\(json)")
                guard let code = json["resCode"] as? Int, code == 0 else {
                   complete(false)
                   return
               }
               complete(true)
            }
        }
        
        func requestCheck() {
            postUrl(checkUrl,params: params) { (resp) in
                guard let json = resp.result.any as? [String: Any],
                    let code = json["resCode"] as? Int, code == 0 else {
    //                complete(false)
                    return
                }
    //           requestSave()
            }
        }
        requestCheck()
        requestSave()
        
    }
}
